import 'package:flutter/material.dart';
import 'di/service_locator.dart';
import 'theme/app_theme.dart';
import 'screens/record_screen.dart';
import 'screens/moon_companion_screen.dart';
import 'screens/settings_screen.dart';
import 'screens/analysis_screen.dart';
import 'screens/terms_policy_dialog.dart';
import 'screens/mode_selection_screen.dart';
import 'screens/profile_completion_screen.dart';
import 'screens/minimalist_mode_screen.dart';
import 'screens/main_screen.dart';
import 'screens/pregnancy_mode_dialog.dart';
import 'screens/pregnancy_preparation_mode_dialog.dart';
import 'screens/parenting_mode_dialog.dart';
import 'screens/period_settings_screen.dart';
import 'screens/health_report_screen.dart';
import 'screens/period_reminder_settings_screen.dart';
import 'screens/pregnancy_screen.dart';
import 'services/app_state_service.dart';
import 'services/app_notifier_provider.dart';
import 'services/app_state_notifier.dart';
import 'services/app_state_provider.dart';

void main() {
  // 确保Flutter绑定在使用任何需要绑定的服务之前被初始化
  WidgetsFlutterBinding.ensureInitialized();
  setupServiceLocator();
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final AppStateNotifier _appStateNotifier = AppStateNotifier();
  bool _isInitialized = false;
  bool _hasUserProfile = false;

  @override
  void initState() {
    super.initState();
    _initializeApp();
  }

  Future<void> _initializeApp() async {
    try {
      await _appStateNotifier.initializeApp();
      
      final hasUserProfile = _appStateNotifier.userProfile != null;
      
      setState(() {
        _isInitialized = true;
        _hasUserProfile = hasUserProfile;
      });
    } catch (e) {
      debugPrint('App initialization failed: $e');
      setState(() {
        _isInitialized = true;
        _hasUserProfile = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    if (!_isInitialized) {
      return MaterialApp(
        home: const Scaffold(
          backgroundColor: Colors.black,
          body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                CircularProgressIndicator(
                  valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                ),
                SizedBox(height: 20),
                Text(
                  '月伴启动中...',
                  style: TextStyle(color: Colors.white, fontSize: 16),
                ),
              ],
            ),
          ),
        ),
      );
    }

    
    if (!_hasUserProfile) {
      return AppNotifierProvider(
        child: AppStateProvider(
          appState: AppStateService(),
          child: MaterialApp(
            title: '月伴',
            theme: AppTheme.theme,
            home: const ProfileCompletionScreen(),
            routes: {
              '/moon_companion': (context) => const MoonCompanionScreen(),
              '/record': (context) => const RecordScreen(),
              '/settings': (context) => const SettingsScreen(),
              '/analysis': (context) => const AnalysisScreen(),
              '/terms_policy': (context) => Scaffold(
                backgroundColor: Colors.black,
                body: const Center(
                  child: TermsPolicyDialog(),
                ),
              ),
              '/mode_selection': (context) => const ModeSelectionScreen(),
              '/profile_completion': (context) => const ProfileCompletionScreen(),
              '/minimalist': (context) => Scaffold(body: const MinimalistModeScreen()),
              '/pregnancy_mode': (context) => Scaffold(body: Center(child: PregnancyModePage())),
              '/pregnancy_preparation_mode': (context) => Scaffold(body: Center(child: PregnancyPreparationModePage())),
              '/parenting_mode': (context) => Scaffold(body: Center(child: ParentingModePage())),
              '/period_settings': (context) => const PeriodSettingsScreen(),
              '/health_report': (context) => const HealthReportScreen(),
              '/period_reminder_settings': (context) => const PeriodReminderSettingsScreen(),
              '/pregnancy': (context) => const PregnancyScreen(),
            },
          ),
        ),
      );
    }

    return AppNotifierProvider(
      child: AppStateProvider(
        appState: AppStateService(),
        child: MaterialApp(
          title: '月伴',
          theme: AppTheme.theme,
          initialRoute: '/',
          routes: {
            '/': (context) => const MainScreen(),
            '/moon_companion': (context) => const MoonCompanionScreen(),
            '/record': (context) => const RecordScreen(),
            '/settings': (context) => const SettingsScreen(),
            '/analysis': (context) => const AnalysisScreen(),
            '/terms_policy': (context) => Scaffold(
              backgroundColor: Colors.black,
              body: const Center(
                child: TermsPolicyDialog(),
              ),
            ),
            '/mode_selection': (context) => const ModeSelectionScreen(),
            '/profile_completion': (context) => const ProfileCompletionScreen(),
            '/minimalist': (context) => Scaffold(body: const MinimalistModeScreen()),
            '/pregnancy_mode': (context) => Scaffold(body: Center(child: PregnancyModePage())),
            '/pregnancy_preparation_mode': (context) => Scaffold(body: Center(child: PregnancyPreparationModePage())),
            '/parenting_mode': (context) => Scaffold(body: Center(child: ParentingModePage())),
            '/period_settings': (context) => const PeriodSettingsScreen(),
            '/health_report': (context) => const HealthReportScreen(),
            '/period_reminder_settings': (context) => const PeriodReminderSettingsScreen(),
            '/pregnancy': (context) => const PregnancyScreen(),
          },
        ),
      ),
    );
  }
}